import React, { useState, useEffect } from 'react';
import classnames from 'classnames';
import moment from 'moment';
import { connect } from 'dva';
import { Button, Form, Select, Table, Empty, Modal, message } from 'antd';
import TPage from '@/modules/TPage';
import CreateModal from './modules/CreateModal';
import Service from '@/public/http/services';
import { DocumentType, OnOrOffState } from '@/public/constant/enums';
import style from './index.css';
const { Option } = Select;
const { Column } = Table;
const List: React.FC<any> = ({ total, list, dispatch }) => {
  const [curPage, setCurPage] = useState(1);
  const [curName, setCurName] = useState(null);

  const pageSize = 10;
  /**
   * 加载列表数据
   */
  function fetchList({ page, name }) {
    dispatch({
      type: 'spec/fetchList',
      payload: {
        page,
        name,
        pageSize
      }
    })
  }

  /**
   * @desc 操作完更新列表
   */
  function reFetchList() {
    fetchList({
      page: curPage,
      name: curName
    })
  }


  useEffect(({ page = curPage, name = curName } = {}) => {
    fetchList({ page, name })
  }, [curPage, curName])
  // 渲染列表查询表单




  // 根据渲染类型渲染列表
  const renderActions =
    (record: any) => {
      const { state } = record;
      return (
        <>


          <Button className={style.mr8} type={'primary'} onClick={() => { handleEdit(record) }}>编辑</Button>
          <Button className={style.mr8} type={'primary'} onClick={() => { hanlledelete(record) }}>删除</Button>
        </>
      );
    }


  const hanlledelete = ({ id }) => {
    Modal.confirm({
      title: '确定删除吗？',
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        Service.deleteGroup(id).then((res) => {
          if(res){
            message.info('删除成功');
            reFetchList();
          }else{
            message.error('规格已绑定商品无法修改');
          }

        })
      }
    });
  }


  const [formModalVisible, setFormModalVisible] = useState(false);
  const [curModalStatus, setCurModalStatus] = useState(0);

  /**
   *
   * @desc 创建
   */
  const handleCreate = () => {
    setCurModalStatus(0);
    setFormModalVisible(true);
  }

  const [curEditInfo, setCurEditInfo] = useState({})
  /**
   *
   * @desc 编辑
   */
  const handleEdit = (record) => {
    setCurModalStatus(1);
    setCurEditInfo(record);
    setFormModalVisible(true);
  }

  /**
   * @desc 创建提交
   */
  const handleSubmit = (formData,valist,status) => {
    const { validateFields, resetFields } = formData;
    validateFields((err, value) => {
      if (!err) {
        const { groupName,valueName } = value;
        var str = ''
        for(let i=0;i<valist.valist.length;i++){
          str += valist.valist[i]+','
        }
        const params = { groupName,valueNames:str};
        (status ? Service.createGroup(params) : Service.updateGroup({ id: curEditInfo['id'], ...params })).then((res) => {
          if(res){
            message.info(`${status ? '添加' : '修改'}成功`);
            resetFields();
            setCurEditInfo({});
            setFormModalVisible(false);
            reFetchList();
          }else{
            message.error('规格已绑定商品无法删除');
          }

        })
      }
    })
  }
  const handleQuery = (query) => {
    setCurPage(1);
    setCurName(query);
  }
  /**
   *
   * @desc 创建/编辑取消
   */
  const handleCancel = (form) => {
    form.resetFields();
    setCurEditInfo({});
    setFormModalVisible(false);
  }

  return (
    <TPage>
      <TPage.Title>规格管理</TPage.Title>
      <TPage.Table>
        <TPage.Layout className={style.btns}>
          <Button type={'primary'} onClick={handleCreate}>新建</Button>
          <TPage.Search
            placeholder={'请输入规格名称，可按回车键搜索'}
            onSearch={handleQuery}
          />
        </TPage.Layout>
        <Table
          className={classnames(style.mt16, style.document_list)}
          locale={{ emptyText: <Empty description={'无数据'} /> }}
          dataSource={list}
          rowKey={(record: any) => record.id}
        >
          <Column title={'编号ID'} width={64} dataIndex={'id'} key={'id'} />
          <Column title={'规格名称'} dataIndex={'groupName'} key={'groupName'} />
          <Column title={'规格值'} dataIndex={'propertyNameList'} key={'propertyNameList'} render={(value) => value?value.map((item,index)=>{return item?item.value+',':''}):''}/>
          <Column title={'创建时间'} dataIndex={'createTime'} key={'createTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
          <Column title={'操作'} key={'act'} render={renderActions} fixed={'right'} />
        </Table>
      </TPage.Table>
      <CreateModal visible={formModalVisible}
                   title={curModalStatus === 0 ? '规格创建' : '规格编辑'}
                   formData={curModalStatus === 0 ? {} : curEditInfo}
                   onOK={(form, data) => handleSubmit(form, data, curModalStatus === 0)}
                   onCancel={handleCancel} />
    </TPage>
  );
}
export default connect((state: any) => {
  return {
    list: state.spec.list,
    total: state.spec.total,
  };
})(List);
